package org.androidpn.net;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.androidpn.model.NetModel;
import org.androidpn.utils.ConstanceUtil;
import org.androidpn.utils.JsonUtil;

public class NetworkAgent {
	// private static final String SERVER_ADDRESS = "http://192.168.43.47:8080";
	private static final String CONTENT_TYPE = "Content-Type";
	private static final String UTF_8 = "UTF-8";

	/**
	 * 接口地址
	 */
	// public static final String URL_USER_REGISTER =
	// "/cuser.do?func=register&";
	// public static final String URL_USER_UPDATE_INFO = "/user/updateInfo";
	// public static final String URL_USER_GET_INFO = "/user/getInfo";
	// public static final String URL_USER_GET_INFO_TEST =
	// "/userinfo/test.json";
	// public static final String URL_MESSAGE_SEND_IMAGE =
	// "/ctalk.do?func=sendImageMessage&";

	public static NetModel request(HashMap<?, ?> content, String requestUrl, HashMap<?, byte[]> bytes) {
		try {
			URL url = new URL(ConstanceUtil.HOST_NAME + requestUrl);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.setConnectTimeout(10000);
			connection.setReadTimeout(10000);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("connection", "keep-alive");
			connection.setRequestProperty("Charsert", "UTF-8");

			if (bytes == null) {

				// 普通表单数据
				connection.setRequestProperty(CONTENT_TYPE, "application/x-www-form-urlencoded");
				// 上传数据
				BufferedWriter out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), UTF_8));
				out.write(getFormString(content).toString());// 要post的数据，多个以&符号分割
				out.flush();
				out.close();
			} else {
				String boundary = java.util.UUID.randomUUID().toString();
				String prefix = "--";
				String lineEnd = "\r\n";
				String charset = "UTF-8";

				// 含多媒体文件数据
				connection.setRequestProperty(CONTENT_TYPE, "multipart/form-data" + ";boundary=" + boundary);

				StringBuilder sb = new StringBuilder();

				for (Map.Entry<?, ?> entry : content.entrySet()) {
					sb.append(prefix);
					sb.append(boundary);
					sb.append(lineEnd);
					sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + lineEnd);
					sb.append("Content-Type: text/plain; charset=" + charset + lineEnd);
					sb.append("Content-Transfer-Encoding: 8bit" + lineEnd);
					sb.append(lineEnd);
					sb.append(entry.getValue());
					sb.append(lineEnd);

				}

				DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
				outStream.write(sb.toString().getBytes());
				for (Map.Entry<?, ?> entry : bytes.entrySet()) {
					byte[] b = (byte[]) entry.getValue();
					if (b != null) {

						StringBuilder sb1 = new StringBuilder();
						sb1.append(prefix);
						sb1.append(boundary);
						sb1.append(lineEnd);
						String name = String.valueOf(entry.getKey());
						sb1.append("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + name + "\""
								+ lineEnd);

						sb1.append("Content-Type: application/octet-stream" + lineEnd);
						sb1.append(lineEnd);

						outStream.write(sb1.toString().getBytes());
						outStream.write(b, 0, b.length);
						outStream.write(lineEnd.getBytes());
					}
				}
				byte[] end_data = (prefix + boundary + prefix + lineEnd).getBytes();
				outStream.write(end_data);
				outStream.flush();
				outStream.close();
			}

			// 读取post之后的返回值
			InputStream inputStream = (InputStream) connection.getInputStream();
			BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
			String line = null;
			StringBuilder sb = new StringBuilder();
			while ((line = in.readLine()) != null) {
				sb.append(line);
			}
			in.close();

			NetModel netModel = new NetModel();
			if (sb.length() > 0) {
				netModel = JsonUtil.parseObject(sb.toString(), NetModel.class);
			}
			connection.disconnect();// 断开连接
			return netModel;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private static StringBuffer getFormString(HashMap<?, ?> params) {
		StringBuffer stringBuffer = new StringBuffer("");
		Iterator<?> it = params.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			Object key = entry.getKey();
			Object value = entry.getValue();
			if (null != value) {
				stringBuffer = stringBuffer.append(key.toString() + "=")
						.append(URLEncoder.encode(value.toString()) + "&");
			} else {
				stringBuffer = stringBuffer.append(key.toString() + "=").append("&");
			}
		}

		return stringBuffer;
	}
}
